import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Text,
  Image,
  TouchableOpacity,
  SafeAreaView
} from 'react-native';
import {
  mainBgColorLightGray,
  mainBgColorWhite,
  screenWidth,
  px2dp,
} from '@/styles';
import { msg } from '@/common';
import homeApi from '@/api/home';
import { getGoodsCar } from '@/api/truck';
import { featchGoodsDetail } from '@/api/goods';
import XmSwiper from '../../../components/XmSwiper';
import GoodsDefaultPic from '../../../components/LoadingDefaultPic';
import XmList from '../../../components/XmList';

/*
 * @Author: luoyunhai
 * @Date: 2020-08-16 10:00:00
 * @LastEditors: kanglang
 * @LastEditTime: 2020-10-28 11:31:22
 * @Description: 车辆列表
 */
export default class FourBrandList extends Component {
  static navigationOptions = ({ navigation }) => {
    return {
      title: navigation.getParam('otherParam') ? `${navigation.getParam('otherParam')}专区` : ''
    };
  };

  constructor(props) {
    super(props);
    this.state = {
      bannerList: [],
      bannerArr: [],
      carList: [],
      page: 1,
      size: 6,
      isLoading: true,
      total: 0,
      showFoot: 1, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
      brandId: '',
      categoryId: ''
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { data } = params;
    navigation.setParams({ otherParam: data && data.name });
    this.setState({
      brandId: data && data.id,
      categoryId: data && data.categoryId
    }, () => {
      this.loadData();
    });
    const brandType = data && data.brandType;
    this._getHomeBanner(brandType);
  }

  // 获取轮播图
  _getHomeBanner(code) {
    homeApi.getDefContentInfoListByCode({ code }).then(res => {
      if (res.success) {
        const bannerPic = res.data;
        let bannerArr = [];
        if (bannerPic && bannerPic.length > 0) {
          bannerArr = bannerPic.map((item, index) => {
            item.icon = item.imageId;
            return item;
          });
        }
        this.setState({
          bannerList: bannerPic,
          bannerArr
        });
      }
    });
  }

  carDetails = (data) => {
    featchGoodsDetail({ id: data && data.id }).then((res) => {
      if (res.success && res.data) {
        if (res.data == '2') {
          msg.emit('app:tip', { text: '此商品已下架' });
          return;
        }
        msg.emit('router: goToNext', {
          routeName: 'TruckDetails',
          data
        });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }

  headerComponent = () => {
    const { bannerArr } = this.state;
    return (
      <View style={{ marginBottom: px2dp(30), backgroundColor: mainBgColorWhite }}>
        <View style={{ height: screenWidth * 0.4 }}>
          {bannerArr && bannerArr.length > 0 ?
            <XmSwiper
              imageData={bannerArr}
              swiperStyle={styles.swiperStyle}
              showDot
              duration={2}
              removeClippedSubviews
            /> :
            <GoodsDefaultPic />}
        </View>
      </View>
    );
  }

  partLoadDate = (page, size, brandId, categoryId, type) => {
    const parame = {
      page,
      size,
      brandId,
      categoryId
    };
    getGoodsCar(parame).then(res => {
      let { carList } = this.state;
      const newList = res.data.result;
      if (res.success) {
        if (res.data.total == 0) {
          this.setState({
            isLoading: false,
            showFoot: 0
          });
          return;
        }
        if (res.data.result.length <= 0) {
          this.setState({
            isLoading: false,
            showFoot: 1
          });
          return;
        }

        if (type == 'dropdown') {
          this.setState({ isLoading: false });
          carList = newList.concat(carList);
        } else if (type == 'pullMore') {
          carList = carList.concat(newList);
        }
        this.setState({
          page: this.state.page + 1,
          carList
        });
        if (res.data.result.length <= this.state.size) {
          this.setState({
            isLoading: false,
            showFoot: 1
          });
        }
      } else {
        this.setState({
          isLoading: false,
          showFoot: 0
        });
        msg.emit('app:tip', { text: '获取失败' });
      }
    }).catch(err => {
      this.setState({
        isLoading: false,
        showFoot: 0
      });
    });
  }

  // 下拉刷新
  loadData() {
    this.setState({
      isLoading: true,
      page: 1,
      carList: []
    }, () => {
      this.partLoadDate(this.state.page, this.state.size, this.state.brandId, this.state.categoryId, 'dropdown');
    });
  }

  // 上拉加载更多
  LoadMore() {
    this.setState({ showFoot: 2 });
    this.partLoadDate(this.state.page, this.state.size, this.state.brandId, this.state.categoryId, 'pullMore');
  }

  formatePrice(number) {
    if (number) {
      return (number / 10000).toFixed(2);
    }
  }

  render() {
    const { carList, isLoading, showFoot } = this.state;

    const renderItem = ({ item }) => {
      return (
        <TouchableOpacity
          style={{}}
          onPress={() => this.carDetails(item)}
        >
          <View style={styles.itemWrap}>
            <View>
              <Image
                style={styles.itemImg}
                source={{ uri: item.picFileId }}
              />
            </View>
            <View style={styles.itemRight}>
              <Text style={styles.itemTitle} numberOfLines={1}>{item.name}</Text>
              <Text style={styles.itemParme} numberOfLines={2}>{item.details}</Text>
              <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'flex-end' }}>
                <Text style={styles.priceTitle}>指导价：</Text>
                <Text style={styles.price}>
                  ¥
                  { item.originalPrice && this.formatePrice(item.originalPrice)}
                </Text>
                <Text style={styles.itemDw}> 万</Text>
                <Text style={styles.salesReal}>
                  销量
                  {' '}
                  {item.salesReal}
                </Text>
              </View>

            </View>
          </View>
        </TouchableOpacity>
      );
    };

    return (
      <SafeAreaView style={styles.wrap}>
        <View>
          <XmList
            sources={carList}
            renderItem={renderItem}
            isLoading={isLoading}
            ListHeaderComponent={this.headerComponent()}
            onDropdownRefresh={() => this.loadData()}
            onPullUpMore={() => this.LoadMore()}
            singleKey={item => item.id}
            showFoot={showFoot}
            noText='暂无商品'
          />
        </View>
      </SafeAreaView>
    );
  }

  // 初始化
  init = () => {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { data } = params;
  };
}
const styles = StyleSheet.create({
  container: {
    paddingTop: px2dp(30)
  },
  wrap: {
    height: '100%',
    backgroundColor: mainBgColorLightGray
  },
  itemWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'blue',
    margin: px2dp(30),
    marginTop: px2dp(0),
    padding: px2dp(20),
    backgroundColor: mainBgColorWhite,
    borderRadius: px2dp(10)
  },
  itemImg: {
    width: px2dp(222),
    height: px2dp(159)
  },
  itemRight: {
    marginLeft: px2dp(30)
  },
  itemTitle: {
    fontSize: px2dp(16),
    color: '#333232',
    width: px2dp(400)
  },
  itemParme: {
    height: px2dp(62),
    fontSize: px2dp(12),
    color: '#999896',
    marginTop: px2dp(4),
    marginBottom: px2dp(12),
    width: px2dp(400)
  },
  priceTitle: {
    fontSize: px2dp(12),
    color: '#666562',
  },
  price: {
    fontSize: px2dp(16),
    color: '#343332',
    marginBottom: px2dp(-4)
  },
  itemDw: {
    fontSize: px2dp(14),
    color: '#343332',
    flex: 1,
    marginBottom: px2dp(-4)
  },
  salesReal: {
    fontSize: px2dp(12),
    color: '#999896',
  },
  carTypeImgWrap: {
    marginBottom: px2dp(20),
    marginLeft: px2dp(30),
    marginRight: px2dp(30)
  },
  carTypeImg: {
    width: '100%',
    height: px2dp(360),
  },
  brands: {
    zIndex: 1,
    position: 'absolute',
    left: px2dp(50),
    top: px2dp(80),
    fontSize: px2dp(20),
    fontWeight: 'bold',
    color: mainBgColorWhite,
  },
  iconWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    zIndex: 1,
    position: 'absolute',
    left: px2dp(50),
    top: px2dp(160),
    fontSize: px2dp(20),
    backgroundColor: 'rgba(0,0,0,0.2)',
    paddingTop: px2dp(2),
    paddingBottom: px2dp(2),
    paddingLeft: px2dp(22),
    paddingRight: px2dp(22),
    borderRadius: px2dp(40)
  },
  seeText: {
    color: mainBgColorWhite,
    fontSize: px2dp(10)
  },
  rightIcon: {
    width: px2dp(8),
    marginLeft: px2dp(4)
  },
  swiperStyle: {
    height: '100%',
    width: screenWidth,
    backgroundColor: '#f5f4f2',
    // borderRadius: px2dp(6) * 2
  }

});
